/*
 * create by Littleken at 2019/3/26 16:06
 */
package com.littleken.order.controller;

import com.littleken.order.VO.ResultVO;
import com.littleken.order.dto.OrderDTO;
import com.littleken.order.enums.ResultEnum;
import com.littleken.order.exception.SellException;
import com.littleken.order.param.OrderForm;
import com.littleken.order.service.Impl.OrderServiceImpl;
import com.littleken.order.utils.converter.OrderForm2OrderDTOConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderServiceImpl service;

    @PostMapping("/create")
    public ResultVO create(@Valid OrderForm orderForm,
                       BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm={}", orderForm);
            throw new SellException(ResultEnum.PARAM_ERROR.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        OrderDTO dto = OrderForm2OrderDTOConverter.convert(orderForm);
        //购物车判空
        if(CollectionUtils.isEmpty(dto.getOrderDetailList())){
            log.error("【创建订单】购物车不能为空");
            throw new SellException(ResultEnum.CART_EMPTY);
        }
        OrderDTO createResult = service.create(dto);

        //根据文档，返回orderid订单id
        Map<String,String> map = new HashMap<>();
        map.put("orderId",createResult.getOrderId());
        return ResultVO.success(map);
    }
}
